package pwd

import (
	global "developer_tools/globals"
	"developer_tools/internal"
	"encoding/json"
	"fmt"
	"os"
	"path"
)

var log_ = global.Logger

// Store 用户名和密码的结构体
type Store struct {
	// 用户名
	Username string
	// 密码
	Password string
	// 主机名
	Host string
	// 端口
	Port int
}

// StoreList 存储多个用户名和密码的结构体
type StoreList struct {
	// 存储用户名和密码的路径
	filePath string
	// 存储用户名和密码的数据
	data []Store
}

// NewStoreList 创建一个新的StoreList实例
func NewStoreList() *StoreList {
	var sl = &StoreList{}

	sl.data = []Store{}
	if sl.filePath == "" {
		home, err := os.UserHomeDir()
		if err != nil {
			log_.Errorf("Failed to get user home directory: %v", err)
			return sl
		}
		parentPath := path.Join(home, global.PwdUserSRPath)

		err = internal.CreateFile(parentPath, global.PwdUserName)
		if err != nil {
			log_.Errorf("Failed to create file: %v", err)
			return sl
		}

		fileAbsPath := path.Join(parentPath, global.PwdUserName)
		sl.filePath = fileAbsPath
	}

	return sl
}

func (sl *StoreList) AddStore(store Store) {
	sl.data = append(sl.data, store)
}

func (sl *StoreList) loadStore() []byte {
	data, err := os.ReadFile(sl.filePath)
	if err != nil {
		log_.Errorf("Failed to read file: %v", err)
		return nil
	}

	if len(data) > 0 {
		err = json.Unmarshal(data, &sl.data)
		if err != nil {
			log_.Errorf("Failed to unmarshal store list: %v", err)
			return nil
		}
		log_.Debug("Read store list from file successfully")
		return data
	} else {
		log_.Warn("File is empty")
		return nil
	}
}

// CheckIfExists 替换指定索引的存储
func (sl *StoreList) CheckIfExists(store Store) bool {
	for _, v := range sl.data {
		if store.Host == v.Host && store.Port == v.Port && store.Username == v.Username && store.Password == v.Password {
			return true
		}
	}

	return false
}

func (sl *StoreList) WriteStore(store Store) {
	_ = sl.loadStore()
	exists := sl.CheckIfExists(store)
	if exists {
		log_.Debug("Current SSH Config already exists")
		return
	}

	sl.AddStore(store)
	data, err := json.Marshal(sl.data)
	if err != nil {
		log_.Errorf("Failed to marshal store list: %v", err)
		return
	}
	err = os.WriteFile(sl.filePath, data, 0644)
	if err != nil {
		log_.Errorf("Failed to write to file: %v", err)
		return
	}
	log_.Debug("Write store list to file successfully")
}

// GetStoreList  获取存储的用户名和密码列表, 传递给前端使用
func (sl *StoreList) GetStoreList() []string {
	data := sl.loadStore()
	if data == nil {
		log_.Warn("Store list is empty")
		return []string{}
	} else {
		var result []string
		for _, v := range sl.data {
			result = append(result, fmt.Sprintf("%s:%d", v.Host, v.Port))
		}

		return result
	}
}

// GetStore 获取存储的用户名和密码
func (sl *StoreList) GetStore(host string, port int) Store {
	data := sl.loadStore()
	if data == nil {
		log_.Warn("Store list is empty")
		return Store{}
	} else {
		for _, v := range sl.data {
			if v.Host == host && v.Port == port {
				return v
			}
		}
		return Store{}
	}
}

func (sl *StoreList) saveToFile() {
	data, err := json.Marshal(sl.data)
	if err != nil {
		log_.Errorf("Failed to marshal store list: %v", err)
		return
	}
	err = os.WriteFile(sl.filePath, data, 0644)
	if err != nil {
		log_.Errorf("Failed to write to file: %v", err)
		return
	}
	log_.Debug("Write store list to file successfully")
}

// DeleteStore 用于删除已经存在的用户名和密码
func (sl *StoreList) DeleteStore(host string, port int) error {
	data := sl.loadStore()
	if data == nil {
		log_.Warn("Store list is empty")
		return fmt.Errorf("Store list is empty")
	} else {
		for i := 0; i < len(sl.data); i++ {
			iData := sl.data[i]

			if iData.Host == host && iData.Port == port {
				sl.data = append(sl.data[:i], sl.data[i+1:]...)
			}
		}
		sl.saveToFile()
		return nil
	}
}
